import numpy


# 从source图片中查找wanted图片所在的位置，当置信度大于accuracy时返回找到的最大置信度位置的左上角坐标
def locate(source, wanted, scales=[0.7, 0.8, 0.9, 1.0, 1.1], accuracy=0.6):
    screen_cv2 = cv2.imread(source)
    wanted_cv2 = cv2.imread(wanted)

    best_scale = 1.0
    max_loc = None
    max_val = -1

    for scale in scales:
        # 缩放大图
        resized = cv2.resize(screen_cv2, None, fx=scale, fy=scale)
        if resized.shape[0] < wanted_cv2.shape[0] or resized.shape[1] < wanted_cv2.shape[1]:
            continue

        # 执行匹配
        result = cv2.matchTemplate(resized, wanted_cv2, cv2.TM_CCOEFF_NORMED)
        min_val, current_max_val, min_loc, current_max_loc = cv2.minMaxLoc(result)

        # 更新最佳匹配
        if current_max_val > max_val:
            max_val = current_max_val
            max_loc = current_max_loc
            best_scale = scale

    print(max_val,wanted)
    if max_val >= accuracy:
        # 计算矩形框坐标
        h, w = wanted_cv2.shape[:2]  # 模板高度和宽度
        top_left = (int(max_loc[0] / best_scale), int(max_loc[1] / best_scale))
        bottom_right = (top_left[0] + int(w / best_scale), top_left[1] + int(h / best_scale))

        # top_left = max_loc
        # bottom_right = (top_left[0] + w, top_left[1] + h)

        # 绘制矩形框（绿色，线宽2像素）
        cv2.rectangle(screen_cv2, top_left, bottom_right, (0, 255, 0), 2)

        # 可选：显示匹配分数
        cv2.putText(screen_cv2, f"Score: {max_val:.2f}",
                    (top_left[0], top_left[1] - 10),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)

        # 保存或显示结果
        output_path = "./cache/result.png"
        cv2.imwrite(output_path, screen_cv2)
        # cv2.imshow("Result", screen_cv2)
        # cv2.waitKey(0)
        # cv2.destroyAllWindows()
        return top_left
    else:
        return None


# 从source图片中查找wanted图片所在的位置，当置信度大于accuracy时返回找到的所有位置的左上角坐标（自动去重）
def locate_all(source, wanted, accuracy=0.90):
    """
    从source图片中查找wanted图片所在的位置，当置信度大于accuracy时返回找到的所有位置的左上角坐标（自动去重）


    """
    loc_pos = []
    screen_cv2 = cv2.imread(source)
    wanted_cv2 = cv2.imread(wanted)

    result = cv2.matchTemplate(screen_cv2, wanted_cv2, cv2.TM_CCOEFF_NORMED)
    location = numpy.where(result >= accuracy)

    ex, ey = 0, 0
    for pt in zip(*location[::-1]):
        x = pt[0]
        y = pt[1]

        if (x - ex) + (y - ey) < 15:  # 去掉邻近重复的点
            continue
        ex, ey = x, y

        loc_pos.append([int(x), int(y)])

    return loc_pos


# 给定目标尺寸大小和目标左上角顶点坐标，即可给出目标中心的坐标
def centerOfTouchArea(wantedSize, topLeftPos):
    tlx, tly = topLeftPos
    h_src, w_src, tongdao = wantedSize
    if tlx < 0 or tly < 0 or w_src <= 0 or h_src <= 0:
        return None
    return (tlx + w_src / 2, tly + h_src / 2)


import cv2
import pytesseract


def find_text_position(image_path, target_text, lang='chi_sim+eng', confidence_threshold=60):
    """
    定位图片中指定文字的位置
    :param image_path: 图片路径
    :param target_text: 要查找的文字
    :param lang: 语言（中文需下载语言包）
    :param confidence_threshold: 置信度阈值
    :return: 文字位置列表[(x, y, w, h)]
    """
    # 读取图像并转为RGB格式
    image = cv2.imread(image_path)
    rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    # 使用Tesseract获取文字详细信息
    data = pytesseract.image_to_data(rgb, lang=lang, output_type=pytesseract.Output.DICT)
    print(data)
    # 筛选目标文字
    positions = []
    content = ''.join(data['text'])
    print(content)
    if content.__contains__(target_text):
        i = content.find(target_text) + 1
        x, y, w, h = data['left'][i], data['top'][i], data['width'][i], data['height'][i]
        positions.append((x, y, w, h))
        # 可视化标记
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # 保存结果
        cv2.imwrite('./cache/result.png', image)

    return positions
